/**
 * 
 */
package leetCode;

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.TreeMap;

/**
 * @author zhongfang
 *
 */
public class MaximumSwap {
	public int maximumSwap(int num) {
		String snum = String.valueOf(num);
		PriorityQueue<Character> characters = new PriorityQueue<>((a, b) -> (b - a));
		for (int i = 0; i < snum.length(); i++) {
			char ch = snum.charAt(i);
			characters.add(ch);
		}
		int j = 0;
		while (j < snum.length() && characters.peek().equals(snum.charAt(j))) {
			characters.poll();
			j++;
		}
		if (j == snum.length()) {
			return num;
		}
		// 把第j个设置为堆顶的值，把第j个的值放到最右边的和堆顶值相等的位置
		char ch1 = snum.charAt(j);
		char ch2 = characters.peek();
		int pos1 = j;
		int pos2 = snum.lastIndexOf(ch2);
		StringBuilder sBuilder = new StringBuilder(snum);
		sBuilder.setCharAt(pos1, ch2);
		sBuilder.setCharAt(pos2, ch1);
		return Integer.parseInt(sBuilder.toString());
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(new MaximumSwap().maximumSwap(9973));
	}

}
